package com.mall.cart.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mall.cart.common.domain.Cart;
import com.mall.cart.common.domain.CartItem;
import com.mall.cart.server.mapper.CartMapper;
import com.mall.cart.server.service.CartService;
import com.mall.common.core.domain.Result;
import com.mall.common.redis.service.RedisService;
import com.mall.common.security.utils.SecurityUtils;
import com.mall.product.common.domain.PmsShop;
import com.mall.product.common.domain.PmsSkuInfo;
import com.mall.product.remote.PmsSkuInfoRemote;
import com.mall.product.remote.PmsSkuSaleAttrValueRemote;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    private static final String USER_CART = "USER_CART:";
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private PmsSkuInfoRemote pmsSkuInfoRemote;
    @Autowired
    private PmsSkuSaleAttrValueRemote pmsSkuSaleAttrValueRemote;


    @Override
    public Result addCart(CartItem cartItem) {

        /**
         * 只做插入
         */
        cartMapper.addCartItem(cartItem);

        return null;

    }

    @Override
    public Result add(Long skuId) {
        //获取用户信息
        Long userId = SecurityUtils.getLoginUser().getUserid();
        //前台用户点击加入购物车
        //判断是否存在redis购物车
        Boolean b = redisService.hasKey(USER_CART + userId);
        //redis不存在此用户购物车信息
        if (b == false) {
            //查询数据库中是否存在此购物车对象
            List<CartItem> cartItemsByDB = cartMapper.existCart(userId);
            //判断数据库是否存在
            if(cartItemsByDB==null || cartItemsByDB.size()==0){
                //数据库也不存在直接创建redis
                completeMap(skuId,userId);
                return Result.success();
            }
            //如果数据库存在，将返回值便利存入redis并将新加入购物车的也存入
            for (CartItem cartItem : cartItemsByDB) {
                //如果数据库中存在此sku
                completeMap(Long.valueOf(String.valueOf(cartItem.getSkuId())),userId);
            }
            completeMap(skuId,userId);
            return Result.success();
        }

        //redis购物车对象存在
        //判断sku是否存在，不存在创建对象，存在获取对象增加数量
        Map<String, Object> fatherHash = redisService.getCacheMap(USER_CART + userId);
        boolean b1 = fatherHash.containsKey(String.valueOf(skuId));
        if(b1==false){
            //不存在此sku添加
            completeMap(skuId,userId);
            return Result.success();
        }
        //如果存在取到这条数据并进行增加数量
        updateCount(fatherHash,skuId,userId);

        return Result.success();
    }

    @Override
    public Result<List<Cart>> findCartList() {
        //创建返回结果集
        List<CartItem> cartItems = new ArrayList<>();

        Cart cart = new Cart();

        //查询购物车列表
        //1.获取当前登录人id
        Long userId = SecurityUtils.getLoginUser().getUserid();

        //通过登录人id查询购物车列表//缓存
        Map<String, Object> cacheMap = redisService.getCacheMap(USER_CART + userId);

        Collection<Object> values = cacheMap.values();

        for (Object value : cacheMap.values()) {
            CartItem cartItem = new CartItem();
            //转换成cartItem对象
            CartItem cartItemVo = JSONObject.parseObject(JSONObject.toJSONString(value),CartItem.class);
            cartItems.add(cartItemVo);
            //封装成cart对象
        }

        Map<Long, List<CartItem>> groupedBySeller = cartItems.stream().collect(Collectors.groupingBy(CartItem::getSellerId));
        List<Cart> collect = groupedBySeller.entrySet().stream().map(groupSon -> {
            Cart cartByGroup = new Cart();

            String sellerName = groupSon.getValue().get(0).getSellerName();

            cartByGroup.setSellerId(groupSon.getKey());
            cartByGroup.setSellerName(sellerName);
            cartByGroup.setCartItemPoList(groupSon.getValue());

            return cartByGroup;
        }).collect(Collectors.toList());


        System.out.println(collect);


        return Result.success(collect);
    }

    /**
     * 根据skuId字符串删除缓存以及数据库数据
     * @param skuIdListByJson
     */
    @Override
    public void clearCartByPay(String skuIdListByJson) {
        //获取用户信息
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        //先删除缓存
        String [] skuIds = skuIdListByJson.split(",");
        for (String skuId : skuIds) {
            boolean b = redisService.deleteCacheMapValue(USER_CART + userId,skuId);
        }

        //再删除数据库中的数据
        //使用多线程
        cartMapper.deleteCartBySkuId(Arrays.asList(skuIds));
    }

    @Override
    public Result updateSaleCount(Integer skuId, Integer skuCount) {
        //获取登录人信息
        Long userId = SecurityUtils.getLoginUser().getUserid();

        //通过登录人id查询购物车列表//缓存
        Map<String, Object> cacheMap = redisService.getCacheMap(USER_CART + userId);

        Collection<Object> values = cacheMap.values();

        for (Object value : cacheMap.values()) {
            //转换成cartItem对象
            CartItem cartItemVo = JSONObject.parseObject(JSONObject.toJSONString(value),CartItem.class);
            if(String.valueOf(skuId).equals(cartItemVo.getSkuId())){
                cartItemVo.setSkuCount(skuCount);
                completeMap(Long.valueOf(skuId),userId);
                return Result.success("数量改动成功!");
            }
        }
        return null;
    }



    //向redis添加购物车对象集明细
    private Result completeMap(Long skuId,Long userId){
        //不存在此sku添加
        PmsSkuInfo skuInfo = pmsSkuInfoRemote.getInfo(skuId).getData();
        //根据skuInfo的shopId查询店铺信息
        PmsShop pmsShop = pmsSkuInfoRemote.findShopByShopId(skuInfo.getShopId()).getData();
        CartItem cartItem = new CartItem();
        BeanUtils.copyProperties(skuInfo, cartItem);
        cartItem.setIsChecked(1);
        cartItem.setCartItemPrice(skuInfo.getPrice());
        cartItem.setSellerId(pmsShop.getId());
        cartItem.setSellerName(pmsShop.getShopName());
        cartItem.setSkuCount(1);
        cartItem.setSkuPrice(skuInfo.getPrice());
        cartItem.setSkuImg(skuInfo.getSkuDefaultImg());
        cartItem.setSkuId(skuId);
        cartItem.setUserId(userId);
        //查询销售属性
        String pmsSkuSaleAttrValue = pmsSkuSaleAttrValueRemote.findSaleAttrBySkuId(skuId).getData();
        cartItem.setSkuAttr(pmsSkuSaleAttrValue);

        HashMap<String, CartItem> itemMap = new HashMap<>();
        itemMap.put(String.valueOf(skuId), cartItem);
        redisService.setCacheMap(USER_CART + userId, itemMap);

        return Result.success();
    }


    //更新redis店铺数量
    public void updateCount(Map<String,Object> fatherHash,Long skuId,Long userId){
        Object cartItemMap = fatherHash.get(String.valueOf(skuId));
        //转JSON
        String cartItemJson = JSONObject.toJSONString(cartItemMap);
        //转对象
        CartItem cartItem = JSONObject.parseObject(cartItemJson, CartItem.class);
        //赋值修改数量和总价
        cartItem.setSkuCount(cartItem.getSkuCount()+1);
        BigDecimal bigDecimalCount = new BigDecimal(cartItem.getSkuCount().toString());
        cartItem.setCartItemPrice(cartItem.getCartItemPrice().multiply(bigDecimalCount));
        HashMap<String, Object> sonMap = new HashMap<>();
        sonMap.put(String.valueOf(skuId),cartItem);
        redisService.setCacheMap(USER_CART+userId,sonMap);
    }


}
